package com.cqie.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cqie.rbac.bo.DepartmentBo;
import com.cqie.rbac.entity.Department;
import com.cqie.rbac.exception.BusinessException;
import com.cqie.rbac.mapper.DepartmentMapper;
import com.cqie.rbac.service.IDepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqie.rbac.util.Result;
import com.cqie.rbac.util.TreeNode;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * <p>
 * 学院表 服务实现类
 * </p>
 *
 * @author 单机吧
 * @since 2021-10-08
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {


    @Override
    public List<Department> DepartmentTree() {
        LambdaQueryWrapper<Department> lqw = Wrappers.lambdaQuery();
        lqw.eq(Department::getParentId,0);
        lqw.orderByAsc(Department::getCreateTime);
        List<Department> departmentList = baseMapper.selectList(lqw);
        if (departmentList != null && departmentList.size() > 0){
            departmentList.forEach(this::DepartmentChildren);
        }
        return departmentList;
    }

    @Override
    public void DepartmentChildren(Department department) {
        LambdaQueryWrapper<Department> lqw = Wrappers.lambdaQuery();
        lqw.eq(Department::getParentId,department.getId());
        lqw.orderByAsc(Department::getCreateTime);
        List<Department> departmentList = baseMapper.selectList(lqw);
        department.setChildren(departmentList);
        if (departmentList != null && departmentList.size() > 0){
            departmentList.forEach(this::DepartmentChildren);
        }
    }

    @Override
    public Department GetDepartmentNameById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public Result UpdateOrAddMenu(DepartmentBo bo) {
        Department department = new Department();
        LambdaQueryWrapper<Department> lqw = Wrappers.lambdaQuery();
        lqw.eq(Department::getDptName,bo.getDptName());
        if (bo.getTag() > 0 || bo.getDptName().equals(bo.getOriginName())){
            if (baseMapper.selectOne(lqw) != null){
                log.error("该院系已存在，新增失败");
                throw new BusinessException("5000", "该院系已存在");
            }
        }
        if(bo.getTag() > 0){

            department.setDptName(bo.getDptName());
            department.setParentId(bo.getParentId());
            if (bo.getTag() > 1){
                department.setParentId(0L);
            }
            baseMapper.insert(department);
        }else {
            department.setId(bo.getId());
            baseMapper.updateById(department);
        }
        return Result.ok();
    }
}
